<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hadd(1,'0')">添加权限</el-button>
        </div>
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button v-if="row.type === 1" type="text" @click="hadd(2,row.id)">添加</el-button>
              <el-button type="text" @click="hedit(row.id)">编辑</el-button>
              <el-button type="text" @click="hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog :visible.sync="showDialog" :title="isEdit?'编辑':'添加'" @closed="hclose">
      <!-- 表单内容 -->
      <el-form ref="formData" label-width="100px" :model="formData" :rules="rules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addPermission, delPermission, getPermissionDetail, getPermissionList, updatePermission } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    const validCode = (rule, value, callback) => {
      let codeList = []
      if (this.isEdit) {
        codeList = this.originerList.filter(item => item.id !== this.formData.id).map(item => item.code)
      } else {
        codeList = this.originerList.map(item => item.code)
      }
      codeList.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    const validName = (rule, value, callback) => {
      let nameList = []
      if (this.isEdit) {
        nameList = this.originerList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id).map(item => item.name)
      } else {
        nameList = this.originerList.filter(item => item.pid === this.formData.pid).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    return {
      list: [],
      showDialog: false,
      isEdit: false,
      formData: {
        name: '',
        id: '',
        type: '',
        code: '',
        description: '',
        pid: '',
        enVisible: ''
      },
      originerList: [],
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入权限描述', trigger: 'blur' },
          { min: 2, max: 50, message: '请输入2~50字符', trigger: 'blur' }
        ] }
    }
  },
  created() {
    this.loadPermissin()
  },
  methods: {
    async  loadPermissin() {
      try {
        const res = await getPermissionList()
        this.originerList = res.data.map(({ id, pid, code, name }) => ({ id, pid, code, name: name.trim() }))
        this.list = tranListToTreeData(res.data)
      } catch (e) {
        console.log(e)
      }
    },
    hadd(type, pid) {
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
      this.isEdit = false
    },
    async hSubmit() {
      const valid = await this.$refs.formData.validate().catch(e => e)
      if (!valid) return
      try {
        let res = null
        if (this.isEdit) {
          res = await updatePermission(this.formData)
        } else {
          res = await addPermission(this.formData)
        }
        this.$message.success(res.message)
        this.showDialog = false
        this.loadPermissin()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    hclose() {
      this.formData = {
        name: '',
        id: '',
        type: '',
        code: '',
        description: '',
        pid: '',
        enVisible: ''
      }
      this.$refs.formData.clearValidate()
    },
    async hedit(id) {
      this.showDialog = true
      this.isEdit = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
    },
    async hdel(id) {
      const result = await this.$confirm('您确认要删除吗？汪汪汪', '提示', { type: 'warning' })
      if (result !== 'confirm') return
      try {
        const res = await delPermission(id)
        this.$message.success(res.message)
        this.showDialog = false
        this.loadPermissin()
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }

}
</script>
